﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text;

namespace MyFeer.Widget.Grid
{
    public class ColTitleTransformer
    {
        public static String GetColTitleString(int col)
        {
            if (col <= 0)
                return "";
            else
            {
                int[] numbers = new int[10];
                int p = 0;
                while (col != 0)
                {
                    numbers[p] = col % 26;
                    col /= 26;
                    p++;
                }
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < p; i++)
                {
                    if (numbers[i] == 0)
                    {
                        if (i != p - 1)
                        {
                            string zStr = "Z";
                            sb.Insert(0, zStr);
                            int j = i;
                            while (numbers[j] == 0)
                            {
                                numbers[j] = 25;
                                j++;
                            }
                            numbers[j]--;
                        }
                    }
                    else
                    {
                        string cStr = ((char)((int)'A' + numbers[i] - 1)).ToString();
                        sb.Insert(0, cStr);
                    }
                }
                return sb.ToString();
            }
        }

        public static int GetColTitleIndex(String titleString)
        {
            int result = 0, power = 1;
            for (int i = titleString.Length - 1; i >= 0; i--)
            {
                char c = titleString[i];
                result += power * GetCharValue(c);
                power *= 26;
            }
            return result;
        }

        /// <summary>
        /// 获取某个字符所代表的值。
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        private static int GetCharValue(char c)
        {
            if (c >= 'A' && c <= 'Z')
                return c - 'A' + 1;
            else if (c >= 'a' && c <= 'z')
                return c - 'a' + 1;
            else
                return 0;
        }
    }
}
